package main.java.com.chegg.coursepicker;

import main.java.com.chegg.coursepicker.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

/**
 *
 *
 *
 */
public class HelloWorld extends HttpServlet {
    private static final String userName1 = "user1@chegg.com";
    private static final String userName2 = "user2@chegg.com";
    private static final int userNumber1 = 1;
    private static final int userNumber2 = 2;

    private static final String password1 = "password1";
    private static final String password2 = "password2";

    private static UserService service = new UserService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        int currentUserId = userName1.equals(username) ? userNumber1 : userNumber2;

        if (isValidLoginCredentials(username, password)) {
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/fwdedTo.jsp");
            try {
                List<String> requiredCourses = service.getRequiredCourses(currentUserId);
                request.setAttribute("courseDescriptions",requiredCourses);
                System.out.println("currentUserId=" + currentUserId);
                request.setAttribute("userId",String.valueOf(currentUserId));
            } catch (Exception e) {
                System.out.println("Error:" + e.getMessage());
                e.printStackTrace();
            }
            dispatcher.forward(request, response);
        } else {
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/loginError.jsp");
            dispatcher.forward(request, response);
        }

        out.close();
    }

    private boolean isValidLoginCredentials(String username, String password) {
        return isValidUser1(username, password)
                || isValidUser2(username, password);
    }

    private boolean isValidUser1(String username, String password) {
        return userName1.equals(username)
                && password1.equals(password);
    }

    private boolean isValidUser2(String username, String password) {
        return userName2.equals(username)
                && password2.equals(password);
    }
}
